//
//  DetailClientViewController.m
//  Marketing
//
//  Created by HanenDev on 16/3/1.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "DetailClientViewController.h"
#import "MyClientCell.h"
#import "NewVisitViewController.h"
#import "SatusSelectViewController.h"
#import "VisitDetailViewController.h"
#import "ManagerNoticeBtnView.h"
#import "VisitHistoryCell.h"
#import "MyTextView.h"
#import "AddPersonController.h"
#import "ContactModel.h"
#import "NewContactView.h"
#import "SetButton.h"
#import "ImageButton.h"
#import "MJRefresh.h"

#define STARTX [UIView getWidth:10]
#define InfoCellH 44.0f //每格的高度
#define TitileW 80.0f //每个标题label的宽度

#import "MapClientViewController.h"
@interface DetailClientViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,StatusSelectDelegate,MapClientViewControllerDelegate,ManagerNoticeBtnViewDelegate,ContactDelegate>
{
    NSArray    *_detailArray;
    NSArray    *_contactArr;
    NSArray    *_otherArr;
    
    CGFloat  longt;
    CGFloat   lati;
    
    CLLocationCoordinate2D lonlat;//地图跳转返回的经纬度
    
    ManagerNoticeBtnView * _topView;
    UIView *firstView;
    UIView *secondView;
    UIView *thirdView;
    UIView *contactView;
    
    NSIndexPath   *NowIndexPathLevel;
    NSIndexPath   *NowIndexPathFrom;
    NSIndexPath   *NowIndexPathStatus;
    
    CGRect  ContactFrame;
    UIView  *addVie;//添加联系人按钮
    
    ImageButton  *_locationBtn;
    UIButton     *btnSave;
    
    CLLocationCoordinate2D coordinate;
    
    NSDictionary  *detailDict;
    int pageNum;
    UIView *footerView;
    NSArray  *clientArr;
}


@property(nonatomic,strong)NSMutableArray    *visitArray;
/**
 *  客户详情
 */
@property(nonatomic,strong)UIView            *detailView;
@property(nonatomic,strong)UIScrollView      *scrollView;
/**
 *  历史拜访
 */
@property(nonatomic,strong)UIView            *visitView;
@property(nonatomic,strong)UITableView       *visitTableView;

@property(nonatomic,strong)UITextField    *companyTF,*levelTF,*fromTF,*statusTF,*addressTF;

@property(nonatomic,strong)UITextField    *principalTF,*personTF,*creTimeTF,*lastTimeTF;//负责人、创建人、创建时间、结束时间
@property(nonatomic,strong)ImageButton       *levelBtn,*formBtn,*statusBtn;

//联系人界面
@property(nonatomic,strong)UITextField    *name1TF,*business1TF,*phone1TF,*mobile1TF,*email1TF;
@property(nonatomic,strong)MyTextView     *remark1TF;

@end

@implementation DetailClientViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = graySectionColor;
    self.navigationItem.hidesBackButton = YES;
    
    self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:self.titleStr];
    
    _topView = [[ManagerNoticeBtnView alloc] initWithFrame:CGRectMake(0, 0, KSCreenW , 35.0f)];
    _topView.backgroundColor = NavBackColor;
    _topView.btnTitleArray =@[@"客户详情",@"历史拜访"];
    _topView.delegate = self;
    [self.view addSubview:_topView];
    
    
    self.navigationItem.leftBarButtonItem=[ViewTool getBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    
    [self createDetailView];
    [self createVisitView];
    [self initData];
    
    [self getRightNavigationBar];
    
    _visitArray = [[NSMutableArray alloc]initWithCapacity:0];
}

- (void)changeNoticeViewWithTitle:(NSString *)btnTitle
{
    if ([btnTitle isEqualToString:@"客户详情"]) {

        self.navigationItem.rightBarButtonItem = nil;
        
        _detailView.hidden = NO;
        _visitView.hidden = YES;
        if (footerView.hidden == NO) {
            footerView.hidden = NO;
        }
    }else if([btnTitle isEqualToString:@"历史拜访"]){
        
        
        self.navigationItem.rightBarButtonItem = [ViewTool getBarButtonItemWithTarget:self WithString:@"HY_nav_icon_add" WithAction:@selector(clickToNewClient:)];
        
        _detailView.hidden = YES;
        _visitView.hidden = NO;
        _visitTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self loadNewData];
        }];
        [_visitTableView.mj_header beginRefreshing];
        
        // 上拉刷新
        _visitTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadMoreData];
            });
        }];
    }
}
#pragma mark -------客户详情界面
- (void)createDetailView{
    
    _detailArray = @[@"公司",@"地址",@"级别",@"来源",@"状态"];
    _contactArr = @[@"姓名",@"职务",@"电话",@"邮箱",@"备注"];
    _otherArr = @[@"负责人",@"创建人",@"创建时间",@"结束时间"];
    
    _detailView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.maxY, KSCreenW, KSCreenH - 64 - _topView.height)];
    [self.view addSubview:_detailView];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, KSCreenH - _topView.height)];
    _scrollView.showsVerticalScrollIndicator=NO;
    [_detailView addSubview:_scrollView];
    _scrollView.backgroundColor = graySectionColor;
    [self createUI];
}
- (void)createUI{
    
    CGFloat tfH    = InfoCellH;
    CGFloat tfW    = KSCreenW - 2*STARTX  - 80.0f;
    
    firstView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 120.0f)];
    [_scrollView addSubview:firstView];
    firstView.backgroundColor = [UIColor whiteColor];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 40)];
    view.backgroundColor = graySectionColor;
    [firstView addSubview:view];
    
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(STARTX, 8, 5, view.height - 16)];
    [view addSubview:imageView1];
    
    UILabel *basicLabel = [[UILabel alloc]initWithFrame:CGRectMake(STARTX, view.height - 20, 200, 20)];
    basicLabel.text = @"客户信息";
    [ViewTool setLableFont12:basicLabel];
    basicLabel.textColor = blackFontColor;
    [view addSubview:basicLabel];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, view.height - 1, KSCreenW , 1)];
    lineView.backgroundColor = grayLineColor;
    [view addSubview:lineView];
    
    for (int i = 0; i<_detailArray.count; i++) {
        UILabel *label = [ViewTool getLabelWith:CGRectMake(STARTX, view.maxY + (InfoCellH * i), 80.0f, InfoCellH) WithTitle:_detailArray[i] WithFontSize:16.0f WithTitleColor:grayFontColor WithTextAlignment:NSTextAlignmentLeft];
        [ViewTool setLableFont13:label];
        [firstView addSubview:label];
        
        if (i != _detailArray.count - 1) {
            UIView *line = [ViewTool getLineViewWith:CGRectMake(STARTX, view.maxY +InfoCellH*(i+1) -1 , KSCreenW - STARTX, 1) withBackgroudColor:grayLineColor];
            [firstView addSubview:line];
        }else{
            UIView *line = [ViewTool getLineViewWith:CGRectMake(0, view.maxY +InfoCellH*(i+1) -1 , KSCreenW, 1) withBackgroudColor:grayLineColor];
            [firstView addSubview:line];
        }
        
    }
    
    _companyTF = [self addTextFieldWithFrame:CGRectMake(STARTX + 80.0f, view.maxY , tfW, tfH) AndStr:@"请添加公司(必填)" WithTrue:YES];
    [firstView addSubview:_companyTF];
    
    
    _addressTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _companyTF.maxY , tfW - STARTX, tfH)  AndStr:@"请输入地址(必填)" WithTrue:NO];
    [firstView addSubview:_addressTF];
    
    
    _locationBtn = [[ImageButton alloc]initWithFrame:CGRectMake(_addressTF.x, _addressTF.y + InfoCellH / 2.0f  -  40 / 2.0f, KSCreenW - _addressTF.x, 40)];
    [_locationBtn addTarget:self action:@selector(jumpToMap) forControlEvents:UIControlEventTouchUpInside];
    [_locationBtn setImage:[UIImage imageNamed:@"HY_list_icon_arrow"] forState:UIControlStateNormal];
    [firstView addSubview:_locationBtn];
    
    _levelTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _addressTF.maxY , tfW - 30, tfH) AndStr:@"请选择级别(必填)" WithTrue:NO];
    [firstView addSubview:_levelTF];
    
    _levelBtn = [[ImageButton alloc]initWithFrame:CGRectMake(_companyTF.x, _levelTF.y + InfoCellH / 2.0 - 40/2, KSCreenW - _levelTF.x, 40)];
//    _levelBtn.backgroundColor = [UIColor redColor];
    [_levelBtn addTarget:self action:@selector(clickToSelect:) forControlEvents:UIControlEventTouchUpInside];
    [_levelBtn setImage:[UIImage imageNamed:@"HY_list_icon_arrow"] forState:UIControlStateNormal];
    _levelBtn.tag = 1000;
    [firstView addSubview:_levelBtn];
    
    _fromTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _levelTF.maxY , tfW -30, tfH) AndStr:@"请选择来源(必填)" WithTrue:NO];
    [firstView addSubview:_fromTF];
    
    _formBtn = [[ImageButton alloc]initWithFrame:CGRectMake(_companyTF.x, _fromTF.y + InfoCellH / 2.0 - 40/2, KSCreenW - _fromTF.x, 40)];
//    _formBtn.backgroundColor = [UIColor redColor];
    [_formBtn addTarget:self action:@selector(clickToSelect:) forControlEvents:UIControlEventTouchUpInside];
    [_formBtn setImage:[UIImage imageNamed:@"HY_list_icon_arrow"] forState:UIControlStateNormal];
    _formBtn.tag = 2000;
    [firstView addSubview:_formBtn];
    
    _statusTF = [self addTextFieldWithFrame:CGRectMake(_companyTF.x, _fromTF.maxY, tfW - 30, tfH) AndStr:@"请选择状态(必填)" WithTrue:NO];
    [firstView addSubview:_statusTF];
    
    _statusBtn = [[ImageButton alloc]initWithFrame:CGRectMake(_companyTF.x, _statusTF.y + InfoCellH / 2.0 - 40/2, KSCreenW - _statusTF.x, 40)];
//    _statusBtn.backgroundColor = [UIColor redColor];
    [_statusBtn addTarget:self action:@selector(clickToSelect:) forControlEvents:UIControlEventTouchUpInside];
    [_statusBtn setImage:[UIImage imageNamed:@"HY_list_icon_arrow"] forState:UIControlStateNormal];
    _statusBtn.tag = 3000;
    [firstView addSubview:_statusBtn];
    
    firstView.frame = CGRectMake(0, 0, KSCreenW, _statusTF.maxY);
    
    NSLog(@"frame -- %@ -- %@",NSStringFromCGRect(_statusTF.frame),NSStringFromCGRect(firstView.frame));
    [self initUI];
}
- (void)initUI{
    
    secondView = [[UIView alloc]initWithFrame:CGRectMake(0, firstView.maxY , KSCreenW, 120.0f)];
    secondView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:secondView];
    
    
    NewContactView  *newContact1 = [[NewContactView alloc] initWithFrame:CGRectMake(0, 0, KSCreenW, [UIView getWidth:120.0f])];
    ContactFrame = newContact1.frame;
    [secondView addSubview:newContact1];
    
    
    addVie = [ViewTool getLineViewWith:CGRectMake(0, newContact1.maxY, KSCreenW, InfoCellH + 17.0f) withBackgroudColor:[UIColor whiteColor]];
    [secondView addSubview:addVie];
    
    UIView *viewLine = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 17.0f) withBackgroudColor:graySectionColor];
    [addVie addSubview:viewLine];
    
    UIView *l2 = [ViewTool getLineViewWith:CGRectMake(0, viewLine.height - 1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [viewLine addSubview:l2];
    
    UIView *l3 = [ViewTool getLineViewWith:CGRectMake(0, addVie.height - 1, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [viewLine addSubview:l3];
    
    SetButton *addbtn = [[SetButton alloc] initWithFrame:CGRectMake((KSCreenW - 125)/2, (addVie.height -20)/2, 125, 20)];
    [addbtn setTitle:@"添加联系人" forState:UIControlStateNormal];
    [addbtn setImage:[UIImage imageNamed:@"HY_list_icon_add"] forState:UIControlStateNormal];
    [addbtn addTarget:self action:@selector(addContectPeson) forControlEvents:UIControlEventTouchUpInside];
    addbtn.center = CGPointMake(addVie.width / 2.0f, addVie.height / 2.0f + viewLine.maxY / 2.0f);
    [addbtn setTitleColor:greenBackColor forState:UIControlStateNormal];
    addbtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    [addVie addSubview:addbtn];
    
    SetButton *button = [[SetButton alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, addVie.height)];
//    button.backgroundColor = [UIColor redColor];
    button.userInteractionEnabled = YES;
    [button addTarget:self action:@selector(addContectPeson) forControlEvents:UIControlEventTouchUpInside];
    [addVie addSubview:button];
    
    secondView.frame = CGRectMake(0, firstView.maxY, KSCreenW, addVie.maxY);
    
    
    [self initViews];
    
}

- (void)addContectPeson
{
    AddPersonController *addPersonVC = [[AddPersonController alloc] init];
    addPersonVC.cid = _cID;
    self.isSholudLoadData = YES;
    [self.navigationController pushViewController:addPersonVC animated:YES];
}


#pragma mark-----跳转地图
- (void)jumpToMap
{
    footerView.hidden = NO;
    _scrollView.frame = CGRectMake(0, 0, KSCreenW, KSCreenH - _topView.maxY - footerView.height);
    
    MapClientViewController * mapVC = [[MapClientViewController alloc] init];
    if (longt == 0&&lati == 0) {
        mapVC.result = 1;
    }else{
        mapVC.locationLongide = [NSString stringWithFormat:@"%f",longt];
        mapVC.locationLatitude =  [NSString stringWithFormat:@"%f",lati];
    }
    mapVC.delegate = self;
    [self.navigationController pushViewController:mapVC animated:YES];
    
    NSLog(@"%@++++++-------",mapVC.locationLatitude);
    
}
#pragma mark --地图代理返回值
- (void)getClickPlaceName:(NSString *)PlaceString withCoordinat2D:(CLLocationCoordinate2D)pt{
    if(![_addressTF.text isEqualToString:PlaceString]){
        _addressTF.text = PlaceString;
    }
    
    lonlat = pt;
}
- (void)initViews{
    CGFloat labelH = InfoCellH;
    CGFloat tfH    = InfoCellH;
    CGFloat tfW    = KSCreenW-2*STARTX - 80.0f;
    
    thirdView = [[UIView alloc]initWithFrame:CGRectMake(0, secondView.maxY, KSCreenW, 100.0f)];
    
    thirdView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:thirdView];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 40.0f)];
    view.backgroundColor = graySectionColor;
    [thirdView addSubview:view];
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 1.0f)];
    view.backgroundColor = graySectionColor;
    [view addSubview:view1];
    
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(STARTX, 8, 5, view.height - 16)];
    [view addSubview:imageView1];
    
    UILabel *basicLabel = [[UILabel alloc]initWithFrame:CGRectMake(STARTX, view.height - 20, 200, 20)];
    basicLabel.text = @"其他";
    [ViewTool setLableFont12:basicLabel];
    
    basicLabel.textColor = blackFontColor;
    [view addSubview:basicLabel];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, view.height - 1, KSCreenW , 1)];
    lineView.backgroundColor = grayLineColor;
    [view addSubview:lineView];
    
    for (int i = 0; i<_otherArr.count; i++) {
        UILabel *label = [ViewTool getLabelWith:CGRectMake(STARTX, view.maxY + InfoCellH * i, KSCreenW, labelH) WithTitle:_otherArr[i] WithFontSize:16.0f WithTitleColor:grayFontColor WithTextAlignment:NSTextAlignmentLeft];
        [ViewTool setLableFont13:label];
        [thirdView addSubview:label];
        
        UIView *line = [ViewTool getLineViewWith:CGRectMake(STARTX, view.maxY +InfoCellH*(i+1) -1, KSCreenW - STARTX, 1) withBackgroudColor:grayLineColor];
        [thirdView addSubview:line];
        if (i == _otherArr.count - 1) {
            line.frame = CGRectMake(0, view.maxY +InfoCellH*(i+1) -1, KSCreenW, 1);
        }
    }
    
    _principalTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, view.maxY, tfW, tfH) AndStr:@"请填写负责人" WithTrue:NO];
    [thirdView addSubview:_principalTF];
    
    _personTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, _principalTF.maxY , _principalTF.width, tfH) AndStr:@"请填写创建人" WithTrue:NO];
    [thirdView addSubview:_personTF];
    
    _creTimeTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, _personTF.maxY , _principalTF.width, tfH) AndStr:@"请填写创建时间" WithTrue:NO];
    [thirdView addSubview:_creTimeTF];
    
    _lastTimeTF = [self addTextFieldWithFrame:CGRectMake(STARTX + TitileW, _creTimeTF.maxY , _principalTF.width, tfH) AndStr:@"请填写最后修改时间" WithTrue:NO];
    [thirdView addSubview:_lastTimeTF];
    thirdView.frame = CGRectMake(0, secondView.maxY, KSCreenW, _lastTimeTF.maxY);
    
    [_scrollView setContentSize:CGSizeMake(KSCreenW, thirdView.maxY + 2 + 64)];
    
}
#pragma mark
#pragma mark-------tableView
- (void)createVisitView{
    _visitView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.maxY, KSCreenW, KSCreenH - 64 - _topView.height)];
    _visitView.hidden = YES;
    [self.view addSubview:_visitView];
    
    _visitTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,KSCreenW, _visitView.height) style:UITableViewStylePlain];
    _visitTableView.delegate = self;
    _visitTableView.dataSource = self;
    _visitTableView.backgroundColor = graySectionColor;
    _visitTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_visitView addSubview:_visitTableView];
    
    
}
- (void)loadNewData{
    pageNum = 1;
    [_visitArray removeAllObjects];
    [self requestHistoryData];
    
}
- (void)loadMoreData{
    pageNum ++;
    [self requestHistoryData];
}


#pragma mark
#pragma mark-----tableView的协议方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [VisitHistoryCell cellHeight];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _visitArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    VisitHistoryCell *cell = [VisitHistoryCell cellWithTableView:tableView WithIndex:indexPath.row];
    if (_visitArray.count >0) {
        ClientModel *client = _visitArray[indexPath.row];
        if (indexPath.row == _visitArray.count -1) {
            cell.lineView.frame = CGRectMake(0, [VisitHistoryCell cellHeight] - 1, KSCreenW, 1);
        }else{
            cell.lineView.frame = CGRectMake(cell.companyLabel.x, [VisitHistoryCell cellHeight] - 1, KSCreenW, 1);
        }
        cell.model = client;
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ClientModel *client = _visitArray[indexPath.row];
    VisitDetailViewController *vc= [[VisitDetailViewController alloc]init];
    vc.visitId = client.clientId;
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark-- 新建拜访
- (void)clickToNewClient:(UIButton *)btn{
    
    CATransition* transition = [CATransition animation];
    transition.type = kCATransitionMoveIn;//可更改为其他方式
    transition.subtype = kCATransitionFromTop;//可更改为其他方式
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    
    NewVisitViewController *vc = [[NewVisitViewController alloc]init];
    vc.clientModel = _model;
    [self.navigationController pushViewController:vc animated:NO];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    footerView.hidden = NO;
    _scrollView.frame = CGRectMake(0, 0, KSCreenW, KSCreenH - _topView.maxY - footerView.height);
}

- (void)goToBack{
    
    if (footerView.hidden == NO) {
        ZLAlertView *alert = [[ZLAlertView alloc]initWithTitle:@"提示" message:@"未保存修改是否返回"];
        [alert addBtnTitle:@"否" action:^{
            
        }];
        [alert addBtnTitle:@"是" action:^{
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alert showAlertWithSender:self];
    }else{
    [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)goToBack11{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    if (self.isSholudLoadData) {
        [self initData];
        
    }else{
        //不需要重新加载数据 只是跳转选择地址
    }
    self.isSholudLoadData = NO;//完成后再设置为默认的 出现就加载数据
}

-(UITextField *)addTextFieldWithFrame:(CGRect)frame AndStr:(NSString *)placeholder WithTrue:(BOOL)ture
{
    UITextField *textF=[[UITextField alloc]initWithFrame:frame];
    textF.userInteractionEnabled = ture;
    textF.textColor = blackFontColor;
    textF.placeholder=placeholder;
    textF.delegate = self;
    [textF setValue:placeholderGrayFontColor forKeyPath:@"_placeholderLabel.textColor"];
    [ViewTool setTFPlaceholderFont14:textF];
    return textF;
}

- (void)getRightNavigationBar{
    
    footerView = [[UIView alloc]initWithFrame:CGRectMake(0, _detailView.height - 70, KSCreenW, 70)];
    footerView.hidden = YES;
    footerView.backgroundColor = [UIColor whiteColor];
    [_detailView addSubview:footerView];
    
    UIButton *outLoginBtn = [[UIButton alloc]initWithFrame:CGRectMake(13, 8, footerView.width - 20, footerView.height - 10)];
    [outLoginBtn setTitle:@"确定保存" forState:UIControlStateNormal];
    [outLoginBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_normal.png"] forState:UIControlStateNormal];
    [outLoginBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_press.png"] forState:UIControlStateHighlighted];
    [outLoginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [outLoginBtn addTarget:self action:@selector(saveClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:outLoginBtn];
    
    UIView *line3 = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [footerView addSubview:line3];
    
}

- (UIButton *)createButtonWithFrame:(CGRect)frame WithTitle:(NSString *)string WithFont:(CGFloat)font WithTag:(CGFloat)tag WithColor:(UIColor *)color
{
    UIButton *btn = [[UIButton alloc]initWithFrame:frame];
    [btn setTitle:string forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:font];
    [btn setTitleColor:color forState:UIControlStateNormal];
    btn.tag = tag;
    [btn addTarget:self action:@selector(clickToSelect:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}
#pragma mark
#pragma mark -------数据字典选择
- (void)clickToSelect:(ImageButton *)btn{
//    [self getRightNavigationBar];
    footerView.hidden = NO;
    _scrollView.frame = CGRectMake(0, 0, KSCreenW, KSCreenH - _topView.maxY - footerView.height);
    
    SatusSelectViewController *vc = [[SatusSelectViewController alloc]init];
    vc.delegate =self;
    vc.num = btn.tag;
    
    switch (btn.tag) {
        case 1000:
        {
            vc.ar = _levelArray;
            vc.itemTitle = @"等级";
            if (_levelTF.text) {
                vc.valuetTitle = _levelTF.text;
            }
            if (NowIndexPathLevel) {
                vc.chooseIndexPath = NowIndexPathLevel;//把前面选择的传到后面
            }
            vc.isLevelOrFromOrStatusType = 1;
        }
            break;
        case 2000:
        {
            vc.itemTitle = @"来源";
            vc.ar = _fromArray;
            if (_fromTF.text) {
                vc.valuetTitle = _fromTF.text;
            }
            if (NowIndexPathFrom) {
                vc.chooseIndexPath = NowIndexPathFrom;//把前面选择的传到后面
            }
            vc.isLevelOrFromOrStatusType = 2;
        }
            break;
        case 3000:
        {
            vc.itemTitle = @"客户状态";
            vc.ar = _statusArray;
            if (_statusTF.text) {
                vc.valuetTitle = _statusTF.text;
            }
            if (NowIndexPathStatus) {
                vc.chooseIndexPath = NowIndexPathStatus;//把前面选择的传到后面
            }
            vc.isLevelOrFromOrStatusType = 3;
        }
            break;
        default:
            break;
    }
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)selectStatusWith:(NSString *)string withNum:(NSInteger)count withInt:(int)number withIndexPath:(NSIndexPath *)indexPath withType:(int)type{
    
    if (count == 1000) {
        _levelTF.text = string;
        NowIndexPathLevel = indexPath;
        if (![string isEqualToString:detailDict[@"levelname"]]) {
        }
    }else if (count == 2000){
        _fromTF.text = string;
        NowIndexPathFrom = indexPath;
        if (![string isEqualToString:detailDict[@"sourcename"]]) {
        }
    }else if(count == 3000){
        _statusTF.text = string;
        NowIndexPathStatus = indexPath;
        if (![string isEqualToString:detailDict[@"statusname"]]) {
        }
    }
    
}
#pragma mark--------- contactdelegate
- (void)endEditing{
    footerView.hidden = NO;
    _scrollView.frame = CGRectMake(0, 0, KSCreenW, KSCreenH - _topView.maxY - footerView.height);
}
#pragma mark--------- 我的客户详情
- (void)initData{
    NSNumber *cidNum =[NSNumber numberWithInt:_cID];
    
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"cid":cidNum };
    [DataTool postWithUrl:DETAIL_CLIENT_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [DataTool changeType:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
        NSLog(@"%@++++++客户详情",jsonDic);
        id json = [DataTool changeType:jsonDic];
        NSArray *clientArray = json[@"contactsList"];
        clientArr = clientArray;
        
        if (clientArray.count > 0) {
            for (UIView *v in secondView.subviews) {
                if ([v isKindOfClass:[NewContactView class]]) {
                    [v removeFromSuperview];
                }
            }
            for(int i = 0;i < clientArray.count;i++){
                NSDictionary *dict = clientArray[i];
                NewContactView *newContect = [[NewContactView alloc] initWithFrame:CGRectMake(0, ContactFrame.size.height * i, KSCreenW, ContactFrame.size.height)];
                newContect.tag = 112233+i;
                
                newContect.delegate = self;
                
                newContect.nameTF.text = dict[@"name"];
                newContect.businessTF.text = dict[@"position"];
                newContect.phoneTF.text = dict[@"phone"];
                newContect.emailTF.text = dict[@"email"];
                newContect.remarkTF.text = dict[@"remark"];
//                newContect.title = dict[@"remark"];//设置remark自适应高度
                
                [secondView addSubview:newContect];
                
                if (i == clientArray.count - 1) {
                    //最后一个联系人的添加 改变一个frame
                    CGRect frame = addVie.frame;
                    frame.origin.y = newContect.maxY;
                    addVie.frame = frame;
                    
                    CGRect secondFrame = secondView.frame;
                    secondFrame.size.height = addVie.maxY;
                    secondView.frame = secondFrame;
                    
                    CGRect thirdFrame = thirdView.frame;
                    thirdFrame.origin.y = secondView.maxY;
                    thirdView.frame = thirdFrame;
                    _scrollView.contentSize = CGSizeMake(KSCreenW, thirdView.maxY + 10 + 64);
                }
            }

        }
        
        _companyTF.text = json[@"customer"][@"company"];
        _levelTF.text = json[@"customer"][@"levelname"];
        _fromTF.text = json[@"customer"][@"sourcename"];
        _statusTF.text = json[@"customer"][@"statusname"];
        detailDict = json[@"customer"];
        
        _addressTF.text = json[@"customer"][@"address"];
        _personTF.text = json[@"customer"][@"creatername"];
        _principalTF.text = json[@"customer"][@"uidname"];
        _creTimeTF.text = json[@"customer"][@"addtime"];
        _lastTimeTF.text = json[@"customer"][@"updatetime"];
        longt = [json[@"customer"][@"lon"] floatValue];
        lati =[json[@"customer"][@"lat"] floatValue] ;
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        [self.view makeToast:error.localizedDescription];
    }];
    
}
#pragma mark-------修改客户详情
- (void)saveClick:(UIButton *)btn{
    
    if (_levelTF.text == nil | [_levelTF.text length] == 0 ){
        [self.view makeToast:@"请选择级别"];
        return;
    }else if (_fromTF.text == nil | [_fromTF.text length] == 0 ){
        [self.view makeToast:@"请选择来源"];
        return;
    }else if (_statusTF.text == nil | [_statusTF.text length] == 0 ){
        [self.view makeToast:@"请选择状态"];
        return;
    }else if (_addressTF.text == nil | [_addressTF.text length] == 0 ){
        [self.view makeToast:@"请填写地址"];
        return;
    }
    
    ZLAlertView *alert = [[ZLAlertView alloc]initWithTitle:@"" message:@"是否保存修改"];
    [alert addBtnTitle:@"否" action:^{
        
    }];
    [alert addBtnTitle:@"是" action:^{
        [self dataWithDetailCustomer];
    }];
    [alert showAlertWithSender:self];
    
}

- (void)dataWithDetailCustomer{
    
    int a1;
    int b1;
    int c1;
    
    a1 = (int)[_levelArray indexOfObject:_levelTF.text] + 1;
    b1 = (int)[_fromArray indexOfObject:_fromTF.text] + 1;
    c1 = (int)[_statusArray indexOfObject:_statusTF.text] + 1;
    
    NSLog(@"级别%d 来源%d 状态%d 客户id%d ",a1,b1,c1,_cID);
    NSLog(@"%@ url",MODIFY_DETAIL_CLIENT_URL);
    NSNumber *cidNum =[NSNumber numberWithInt:_cID];
    NSNumber *levelNum =[NSNumber numberWithInt:a1];
    NSNumber *fromNum =[NSNumber numberWithInt:b1];
    NSNumber *statusNum =[NSNumber numberWithInt:c1];
    NSMutableDictionary * dic =[NSMutableDictionary dictionaryWithDictionary:@{@"token":TOKEN,@"uid":@(UID),@"id":cidNum,@"level":levelNum,@"source":fromNum,@"status":statusNum,@"company":_companyTF.text,@"address":_addressTF.text}];
    
    NSString *lon;
    NSString *lat;
    if (lonlat.longitude && lonlat.latitude) {
        lon = [NSString stringWithFormat:@"%.6f",lonlat.longitude];
        lat = [NSString stringWithFormat:@"%.6f",lonlat.latitude];
    }else{
        lon = [NSString stringWithFormat:@"%.6f",longt];
        lat = [NSString stringWithFormat:@"%.6f",lati];
    }
    [dic setObject:lon forKey:@"lon"];
    [dic setObject:lat forKey:@"lat"];
    
    NSLog(@"%@ dic++++++++",dic);
    [DataTool postWithUrl:MODIFY_DETAIL_CLIENT_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",jsonDic);
        if ([[jsonDic[@"code"]stringValue] isEqualToString:@"100"]) {
            [self dataWithUpdateContact];
        }else{
            [DataTool showMessage:jsonDic[@"message"] view:self];
        }
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
- (void)dataWithUpdateContact{
    
    NSMutableArray *array = [NSMutableArray array];
    for (int i=0; i<clientArr.count; i++) {
        NSDictionary *dict = clientArr[i];
        NewContactView *newContect = [secondView viewWithTag:112233+i];
        ContactModel *model = [[ContactModel alloc]init];
        model.uid = [dict[@"id"] intValue];
        model.cid = [dict[@"cid"] intValue];
        model.name = newContect.nameTF.text;
        model.job = newContect.businessTF.text;
        model.tel = newContect.phoneTF.text;
        model.email = newContect.emailTF.text;
        model.remark = newContect.remarkTF.text;
        [array addObject:model];
    }
    
    for (int i = 0; i <array.count; i++) {
        ContactModel *model = array[i];
        NSLog(@"%@ +++++++model.name",model.name);
        
        NSMutableDictionary * dic =[NSMutableDictionary dictionaryWithDictionary:@{@"token":TOKEN,@"uid":@(UID),@"id":@(model.uid),@"cid":@(model.cid),@"name":model.name,@"position":model.job,@"phone":model.tel,@"email":model.email,@"remark":model.remark}];
        [DataTool postWithUrl:CONTACT_UPDATE_CLIENT_URL parameters:dic success:^(id data) {
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@+++++++++",jsonDic);
            if ([[jsonDic[@"code"]stringValue] isEqualToString:@"100"]) {
                if (i == array.count - 1) {
                    [SVProgressHUD showSuccessWithStatus:jsonDic[@"message"]];
                    footerView.hidden = YES;
                }
            }else{
                [DataTool showMessage:jsonDic[@"message"] view:self];
            }
        } fail:^(NSError *error) {
            NSLog(@"%@",error);
            [self.view makeToast:error.localizedDescription];
        }];
    }
    

}
//我的客户-相关拜访
- (void)requestHistoryData{
    
    NSNumber *cidNum =[NSNumber numberWithInt:_cID];
    NSNumber *pageNum1 = [NSNumber numberWithInt:pageNum];
    NSNumber *rowsNum = [NSNumber numberWithInt:20];
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"cid":cidNum,@"page":pageNum1,@"rows":rowsNum};
    [DataTool postWithUrl:HISTORY_CLIENT_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [SVProgressHUD dismiss];
        if ([jsonDic[@"code"]integerValue] == 200) {
            [DataTool showMessage:jsonDic[@"message"] view:self];
        }
        NSLog(@"%@-----+++++++",jsonDic);
        NSMutableArray *array = jsonDic[@"visitlist"];
        for (int i= 0; i<array.count; i++) {
            ClientModel *client = [[ClientModel alloc]init];
            id dd = [DataTool changeType:array[i]];
            [client setValuesForKeysWithDictionary:dd];
            [_visitArray addObject:client];
        }
        
        [_visitTableView reloadData];
        [_visitTableView.mj_header endRefreshing];
        
        if ([jsonDic[@"visitcount"] integerValue] == _visitArray.count) {
            [_visitTableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [_visitTableView.mj_footer endRefreshing];
        }
        
    } fail:^(NSError *error) {
        [self.view makeToast:error.localizedDescription];
        [_visitTableView.mj_header endRefreshing];
        [_visitTableView.mj_footer endRefreshing];
    }];
}

@end
